package view;

import entity.ChessUser;
import message.*;
import model.RoomInfo;
import socket.ChessClient;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 房间列表界面.
 *
 * @author 张天羿
 */
public class RoomList extends JFrame {
    ChessUser chessUser = null;
    GameFrame gameFrame;
    ArrayList<RoomInfo> roomInfos = new ArrayList();

    public RoomList(GameFrame gameFrame, final ChessUser chessUser) {
        this.gameFrame = gameFrame;
        this.chessUser = chessUser;
        ChessClient.getInstance().setRoomList(this);
        this.setTitle("五子棋");
        this.setSize(1000, 700);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setVisible(true);
        mainPanel = new JPanel() {
            protected void paintComponent(Graphics g) {
                Image image = new ImageIcon("resource/img/ting.png").getImage();
                g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
            }
        };
        getContentPane().add(mainPanel, BorderLayout.CENTER);
        mainPanel.setLayout(null);

        initUserList();
        initUserShowPanel();
        initChartShowPanel();
        initChangeChartOrUserPanel();
        initSendPanel();
        initButtonPanel();
        initChoosePanel();
        initRoomList();
        showRoomListPanel(this.roomInfos);

        addAction();

    }

    JPanel mainPanel;//主panel
    JPanel userShowPanel;//用户列表panel
    JPanel chartPanel;//聊天panel
    JPanel sendPanel = new JPanel();//发送按钮panel
    JPanel buttonPanel = new JPanel();//上方按键panel
    JPanel innerChoosePanel = new JPanel();//每个小房间penal
    JPanel choosePanel = new JPanel();//选择房间panel

    JButton changeToUserButton;//切换到用户列表
    JButton changeToChartButton;//切换到聊天模式
    JButton sendButton = new JButton("发送");
    JButton quickGameButton = new JButton("快速游戏");
    JButton logoutButton = new JButton("退出登录");

    JTextField textField = new JTextField();//聊天输入
    JTextArea textArea = new JTextArea();//聊天显示

    JScrollPane chooseScroll = new JScrollPane();//选择房间的滚动条
    JScrollPane chartScroll = new JScrollPane();//聊天的滚动条
    JScrollPane userScroll = new JScrollPane();//用户列表的滚动条

    JList list = new JList();//用户列表

    /**
     * 初始化选择房间界面.
     */
    private void initChoosePanel() {
        chooseScroll.setBounds(0, 4, getWidth() / 7 * 4, getHeight() * 6 / 10);
        chooseScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        chooseScroll.setOpaque(false);
        chooseScroll.setBorder(null);
        chooseScroll.getViewport().setOpaque(false);
        chooseScroll.setViewportView(innerChoosePanel);

        innerChoosePanel.setOpaque(false);
        innerChoosePanel.setLayout(new GridLayout(6, 2, 15, 15));

        choosePanel.setOpaque(false);
        choosePanel.setBounds(getWidth() / 3, getHeight() / 5 - 10, getWidth() / 5 * 3, getHeight() / 5 * 3 + 15);
        choosePanel.setLayout(null);
        choosePanel.add(chooseScroll);

        mainPanel.add(choosePanel);
    }

    /**
     * 初始化在线用户列表组件.
     */
    private void initUserList() {
        list.setCellRenderer(new MyListCellRender());
        list.setOpaque(false);
    }

    /**
     * 初始化按键界面.
     */
    private void initButtonPanel() {
        buttonPanel.setOpaque(false);
        buttonPanel.setBounds(200, 0, 761, 80);
        buttonPanel.setLayout(null);

        quickGameButton.setBounds(187, 13, 127, 30);
        logoutButton.setBounds(625, 13, 108, 30);

        buttonPanel.add(quickGameButton);
        buttonPanel.add(logoutButton);


        mainPanel.add(buttonPanel);
    }

    /**
     * 初始化发送按钮和文本框界面.
     */
    private void initSendPanel() {
        sendPanel.setBounds(10, 630, 230, 35);
        sendPanel.setOpaque(false);

        textField.setBounds(0, 583, 149, 25);
        textField.setColumns(12);
        textField.setVisible(false);

        sendButton.setVisible(false);
        sendButton.setBounds(148, 583, 79, 25);

        sendPanel.add(sendButton);
        sendPanel.add(textField);

        mainPanel.add(sendPanel);

    }

    /**
     * 初始化用户列表和聊天转换界面.
     */
    private void initChangeChartOrUserPanel() {

        changeToUserButton = new JButton() {
            protected void paintComponent(Graphics g) {
                Image image = new ImageIcon("resource/img/bt1.png").getImage();
                g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
            }
        };
        changeToUserButton.setBounds(50, 38, 140, 45);

        changeToChartButton = new JButton() {
            protected void paintComponent(Graphics g) {
                Image image = new ImageIcon("resource/img/bt1small.png").getImage();
                g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
            }
        };
        changeToChartButton.setBounds(70, 10, 100, 40);

        JPanel changePanel = new JPanel();
        changePanel.setBounds(0, 0, 232, 200);
        changePanel.setLayout(null);
        changePanel.setOpaque(false);

        changePanel.add(changeToChartButton);
        changePanel.add(changeToUserButton);

        mainPanel.add(changePanel);
    }

    /**
     * 初始化用户列表界面.
     */
    private void initUserShowPanel() {
        userShowPanel = new JPanel() {
            protected void paintComponent(Graphics g) {
                Image image = new ImageIcon("resource/img/chart.png").getImage();
                g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
            }
        };

        userScroll.setBounds(23, 20, 205, 520);
        userScroll.setOpaque(false);
        userScroll.setBorder(null);
        userScroll.getViewport().setOpaque(false);
        userScroll.setViewportView(list);
        userShowPanel.add(userScroll);

        userShowPanel.setBounds(0, 70, 250, 560);
        userShowPanel.setOpaque(false);
        userShowPanel.setLayout(null);

        mainPanel.add(userShowPanel);
    }

    /**
     * 初始化聊天界面.
     */
    private void initChartShowPanel() {
        chartPanel = new JPanel() {
            protected void paintComponent(Graphics g) {
                Image image = new ImageIcon("resource/img/chart.png").getImage();
                g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
            }
        };
        //
        textArea.setEditable(false);
        textArea.setBounds(23, 20, 205, 520);
        textArea.setOpaque(false);
        textArea.setLineWrap(true);
        //
        chartScroll.setViewportView(textArea);
        chartScroll.setOpaque(false);
        chartScroll.setBorder(null);
        chartScroll.getViewport().setOpaque(false);
        chartScroll.setBounds(23, 20, 205, 520);
        //
        chartPanel.setBounds(0, 70, 250, 560);
        chartPanel.setOpaque(false);
        chartPanel.setVisible(false);
        chartPanel.setLayout(null);

        chartPanel.add(chartScroll);

        mainPanel.add(chartPanel);
    }

    /**
     * 展示单条聊天信息.
     *
     * @param str 发送的内容
     */
    public void showChatMessage(String str) {
        String str1 = this.textArea.getText();
        this.textArea.setText(str1 + "\n" + str + "\n");
        textField.setText("");
        int height = 10;
        Point point = new Point();
        point.setLocation(0, this.textArea.getLineCount() * height);
        this.chartScroll.getViewport().setViewPosition(point);
    }

    //初始化房间列表(测试用)
    private void initRoomList() {
        for (int i = 0; i < 12; i++) {
            RoomInfo roomInfo = new RoomInfo(0, null, null, RoomInfo.NONE);
            roomInfos.add(roomInfo);
        }
    }

    /**
     * 展示传入的房间列表.
     *
     * @param roomInfos 房间列表
     * @see RoomInfo
     */
    public void showRoomListPanel(List<RoomInfo> roomInfos) {
        // TODO Auto-generated method stub
        this.innerChoosePanel.removeAll();
        for (int i = 0; i < roomInfos.size(); i++) {//房间
            final RoomInfo roomInfo = roomInfos.get(i);
            //
            JPanel onlineRoomPanel = new JPanel();
            onlineRoomPanel.setName(i + "");
            onlineRoomPanel.setOpaque(false);
            //
            JButton toLeftRoomButton = new JButton();
            if (roomInfo.getLeftPlayer() != null) {
                ImageIcon icon = new ImageIcon(roomInfos.get(i).getLeftPlayer().getFileName());
                toLeftRoomButton.setIcon(new ImageIcon(icon.getImage().getScaledInstance(45, 45, Image.SCALE_SMOOTH)));
            } else
                toLeftRoomButton.setIcon(new ImageIcon("resource/img/kong.png"));
            toLeftRoomButton.setSize(45, 45);
            toLeftRoomButton.setPreferredSize(new Dimension(45, 45));
            onlineRoomPanel.add(toLeftRoomButton);
            toLeftRoomButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
            //
            Image image = new ImageIcon("resource/img/table.png").getImage().getScaledInstance(80, 80, Image.SCALE_DEFAULT);
            JLabel noUseButton = new JLabel(new ImageIcon(image));
            noUseButton.setSize(80, 80);
            noUseButton.setPreferredSize(new Dimension(80, 80));
            onlineRoomPanel.add(noUseButton);
            //
            JButton toRightRoomButton = new JButton();
            if (roomInfo.getRightPlayer() != null) {
                ImageIcon icon = new ImageIcon(roomInfos.get(i).getRightPlayer().getFileName());
                toRightRoomButton.setIcon(new ImageIcon(icon.getImage().getScaledInstance(45, 45, Image.SCALE_SMOOTH)));
            } else
                toRightRoomButton.setIcon(new ImageIcon("resource/img/kong.png"));
            toRightRoomButton.setSize(45, 45);
            onlineRoomPanel.add(toRightRoomButton);
            toRightRoomButton.setPreferredSize(new Dimension(45, 45));
            toRightRoomButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
            //
            addActionForRoom(toLeftRoomButton, toRightRoomButton);
            innerChoosePanel.add(onlineRoomPanel);
        }
        RoomList.this.validate();//强制刷新主窗口
    }

    /**
     * 展示传入的用户列表.
     *
     * @param userlist
     */
    public void showUserList(final List<ChessUser> userlist) {
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("退出程序");
                OffMessage msg = new OffMessage();
                ChessClient.getInstance().sendMessage(msg);
            }
        });

        final String[] values = new String[userlist.size()];
        list.setModel(new AbstractListModel() {

            @Override
            public int getSize() {

                return userlist.size();
            }

            @Override
            public Object getElementAt(int index) {
                // TODO Auto-generated method stub
                return userlist.get(index);
            }

        });
    }

    /**
     * 为每个小房间左右的?图标挂载点击事件.
     *
     * @param toLeftRoomButton
     * @param toRightRoomButton
     */
    private void addActionForRoom(JButton toLeftRoomButton, JButton toRightRoomButton) {
        toLeftRoomButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //房间左边座位按钮
                int roomid = Integer.parseInt(((JComponent) e.getSource()).getParent().getName());//获得对应房间的名字
                System.out.println("roomId:" + roomid);
                //房间选择报文传输 roomId、username、isLefIt  传输给其他用户的界面
                ClickRoomMessage clickRoomMessage = new ClickRoomMessage(roomid, chessUser, true);
                ChessClient.getInstance().sendMessage(clickRoomMessage);//发给服务器
            }
        });

        toRightRoomButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //房间右边座位按钮
                int roomid = Integer.parseInt(((JComponent) e.getSource())
                        .getParent().getName());//获得对应房间的名字
                System.out.println("roomId:" + roomid);
                //房间选择报文传输 roomId、username、isLeft  传输给其他用户的界面
                ClickRoomMessage clickRoomMessage = new ClickRoomMessage(roomid, chessUser, false);
                ChessClient.getInstance().sendMessage(clickRoomMessage);//发给服务器
            }
        });
    }

    /**
     * 挂载鼠标点击事件.
     */
    private void addAction() {
        changeToChartButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                userShowPanel.setVisible(false);
                chartPanel.setVisible(true);
                changeToChartButton.setBounds(50, 38, 140, 45);
                changeToUserButton.setBounds(70, 10, 100, 40);
                textField.setVisible(true);
                sendButton.setVisible(true);
            }
        });

        changeToUserButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                chartPanel.setVisible(false);
                userShowPanel.setVisible(true);
                changeToUserButton.setBounds(50, 38, 140, 45);
                changeToChartButton.setBounds(70, 10, 100, 40);
                textField.setVisible(false);
                sendButton.setVisible(false);
            }
        });

        textField.addKeyListener(new KeyAdapter() {//聊天回车键事件
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    String str = textField.getText().trim();
                    if (str.length() != 0) {
                        //房间选择报文传输 聊天信息传输给其他用户的界面
                        ClickChatMessage clickChatMessage = new ClickChatMessage(str, chessUser);
                        ChessClient.getInstance().sendMessage(clickChatMessage);//发给服务器

                    }
                }
            }
        });

        sendButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) { //在线聊天发送按钮
                String str = textField.getText().trim();
                //房间选择报文传输 聊天信息传输给其他用户的界面

                if (str.length() != 0) {
                    //房间选择报文传输 聊天信息传输给其他用户的界面
                    ClickChatMessage clickChatMessage = new ClickChatMessage(str, chessUser);
                    ChessClient.getInstance().sendMessage(clickChatMessage);//发给服务器
                }

            }
        });

        quickGameButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {//快速进入按钮
                QuickEnterMessage quickEnterMessage = new QuickEnterMessage(chessUser);
                ChessClient.getInstance().sendMessage(quickEnterMessage);
            }
        });

        logoutButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                LogoutMessage logoutMessage = new LogoutMessage();
                ChessClient.getInstance().sendMessage(logoutMessage);//发给服务器
                toGameFrame();
            }
        });
    }

    /**
     * 去往在线房间.
     *
     * @param roomid
     * @param isleft
     * @param chessUser
     */
    public void toRoom(int roomid, boolean isleft, ChessUser chessUser) {
        new OnlineRoom(roomid, isleft, this, chessUser);
        this.setVisible(false);
    }

    /**
     * 返回游戏大厅.
     */
    public void toGameFrame() {
        // TODO Auto-generated method stub
        gameFrame.setVisible(true);
        this.dispose();
    }

    public static void main(String[] args) {
        new RoomList(null, new ChessUser("123"));
    }

    /**
     * 内部类,生成list格式(借鉴).
     */
    private class MyListCellRender extends JLabel implements ListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            setIcon(new ImageIcon(((ChessUser) value).getFileName()));
            setText(((ChessUser) value).getName());
            return this;
        }
    }
}
